<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-plus"
        @click="handleAdd"
      >新增商品</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="objList"
      border
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column type="expand">
        <template slot-scope="{ row }">
          <el-form label-position="left" class="table-expand">
            <el-form-item label="商品名称">
              <span>{{ row.name }}</span>
            </el-form-item>
            <el-form-item label="商品简介">
              <span>{{ row.remark }}</span>
            </el-form-item>
            <el-form-item label="商品图片">
              <el-image
                class="image"
                :src="imgUrl + '/' + row.img"
                :preview-src-list="[imgUrl + '/' + row.img]"
                fit="cover"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline" />
                </div>
              </el-image>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column
        label="编号"
        align="center"
        width="90px"
        type="index"
        :index="indexMethod"
      />
      <el-table-column label="名称" align="center" width="220px">
        <template slot-scope="{ row }">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="简介"
        align="center"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="{ row }">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="100px"
        class-name="small-padding fixed-width"
        width="100px"
      >
        <template slot-scope="{ row }">
          <el-button
            type="danger"
            size="mini"
            @click="handleDelete(row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-el-drag-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="商品简介" prop="remark">
          <el-input
            v-model="temp.remark"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="所属企业" prop="entId">
          <el-select
            v-model="temp.entId"
            placeholder="请选择"
            :disabled="entFlag"
            class="full-width"
          >
            <el-option
              v-for="item in entOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片" prop="img">
          <el-upload
            ref="uploadImage"
            :action="uploadFileUrl"
            name="file"
            :data="data"
            :auto-upload="false"
            list-type="picture-card"
            :limit="1"
            :on-success="handleSuccess"
            :on-preview="handlePictureCardPreview"
            :on-exceed="handleExceed"
            :on-change="handleChange"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          :disabled="entFlag"
          @click="dialogStatus === 'add' ? addData() : modifiedData()"
        >确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { queryGood, deleteGood, addGood } from '@/api/good'
import elDragDialog from '@/directive/el-drag-dialog'
import store from '@/store'
import { entMixin } from '@/mixins/entMixin'

export default {
  name: 'GoodItem',
  directives: { elDragDialog },
  mixins: [entMixin],
  data() {
    const IMAGE_FILE_NAME = 'goodImage'
    return {
      type: 'good',
      tableKey: 0,
      goodList: null,
      listLoading: true,
      listQuery: {
        id: -1,
        userId: store.getters.token
      },
      data: {
        account: store.getters.token,
        path: IMAGE_FILE_NAME
      },
      temp: {
        name: '',
        remark: '',
        img: '',
        entId: -1,
        userId: store.getters.token
      },
      rules: {
        name: [
          {
            required: true,
            message: '请填写商品名称',
            trigger: 'change'
          }
        ],
        remark: [
          {
            type: 'string',
            required: true,
            message: '请填写商品简介',
            trigger: 'change'
          }
        ],
        entId: [
          {
            required: true,
            message: '请选择企业！',
            trigger: 'change'
          }
        ],
        img: [
          {
            type: 'string',
            required: true,
            message: '请选择商品图片',
            trigger: 'change'
          }
        ]
      },
      dialogStatus: '',
      dialogFormVisible: false,
      dialogVisible: false,
      dialogImageUrl: '',
      textMap: {
        add: '添加商品'
      },
      imgUrl: process.env.VUE_APP_BASE_IMAGE_API + IMAGE_FILE_NAME,
      uploadFileUrl: store.getters.uploadFileUrl
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    // fetchData() {
    //   this.listLoading = true
    //   queryGood(this.listQuery)
    //     .then(response => {
    //       this.goodList = response.good.reverse()
    //       setTimeout(() => {
    //         this.listLoading = false
    //       }, 0.5 * 1000)
    //     })
    //     .catch(error => {
    //       console.log(error)
    //     })
    // },
    resetTemp() {
      this.temp = {
        name: '',
        remark: '',
        img: '',
        entId: this.temp.entId,
        userId: store.getters.token
      }
    },
    handleAdd() {
      this.resetTemp()
      this.dialogStatus = 'add'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    addData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$refs['uploadImage'].submit()
        }
      })
    },
    handleDelete(id) {
      this.$msgbox
        .confirm('您确定要删除这条数据吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          deleteGood({ id })
            .then(response => {
              const index = this.objList.findIndex(v => v.id === id)
              this.objList.splice(index, 1)
              this.$notify({
                title: '提示',
                message: '删除成功！',
                type: 'success',
                duration: 2000
              })
            })
            .catch(error => {
              console.log(error)
              this.$notify({
                title: '提示',
                message: '删除失败！',
                type: 'error',
                duration: 2000
              })
            })
        })
    },
    handleSuccess(response, file, fileList) {
      this.temp.img = response.fileName
      addGood(this.temp).then(response => {
        this.objList.unshift(this.temp)
        this.dialogFormVisible = false
        this.$notify({
          title: '提示',
          message: '添加成功！',
          type: 'success',
          duration: 2000
        })
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleChange(file, fileList) {
      if (this.temp.img === '') {
        this.temp.img = 'hasImage'
      }
    },
    handleRemove(file, fileList) {
      if (fileList.length === 0) {
        this.temp.img = ''
      }
    },
    handleExceed(file) {
      this.$message({
        message: '当前版本只支持上传一张图片！',
        type: 'warning'
      })
    },
    indexMethod(index) {
      return index + 1
    }
  }
}
</script>

<style scoped>
.image {
  width: 250px;
  height: 200px;
  border-radius: 5px;
  background-color: rgb(235,235,235);
  display:flex;
  justify-content: center;
  align-items: center;
}
</style>
